package org.poliglot.syllab;

import java.util.ResourceBundle;

/**
 * Hyphenator Engine implementation that tries to find the syllabification of
 * each word in a resource bundle. The words not found in the resource bundle
 * are syllabified using the default TEX hyphenator.
 *
 * @author: Cristian Constantin
 * @date: 16.05.2010
 */
public class ResourceBundleHyphenator implements HyphenatorEngine
{

    private HyphenatorEngine defaultEngine;
    private ResourceBundle resourceBundle;

    public ResourceBundleHyphenator( HyphenatorEngine defaultEngine, ResourceBundle resourceBundle )
    {
        this.defaultEngine = defaultEngine;
        this.resourceBundle = resourceBundle;
    }

    public String hyphenate( String source )
    {
        StringBuilder sb = new StringBuilder();
        int startIndex = -1, endIndex = -1;
        char c;

        for ( int i = 0; i < source.length(); i++ )
        {
            c = source.charAt( i );

            if ( Character.isWhitespace( c ) )
            {
                if ( startIndex > -1 )
                {
                    sb.append( processWord( source.substring( startIndex, endIndex + 1 ) ) );
                    startIndex = endIndex = -1;
                }

                sb.append( c );
            }
            else
            {
                if ( startIndex == -1 )
                {
                    startIndex = endIndex = i;
                }
                else
                {
                    endIndex++;
                }
            }
        }

        if ( startIndex > -1 )
        {
            sb.append( processWord( source.substring( startIndex, endIndex + 1 ) ) );
        }

        return sb.toString();
    }

    protected String processWord( String word )
    {
        if ( resourceBundle.containsKey( word ) )
        {
            return resourceBundle.getString( word );
        }
        else
        {
            return defaultEngine.hyphenate( word );
        }
    }
}
